﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Security.Credentials;
using Windows.UI.Xaml;

namespace InfoHub.Helpers
{
    public static class PasswordVaultHelper
    {
        private static readonly string AppId = Application.Current.ToString();

        /// <summary>
        /// Returns a stored 'password' ie secret for a given credential name.
        /// Ex. GetPassword("oAuthToken") returns the stored token value.
        /// </summary>
        /// <param name="credentialName"></param>
        /// <returns></returns>
        public static string GetPassword(string credentialName)
        {
            var vault = new PasswordVault();
        
            try
            {
                return vault.Retrieve(AppId, credentialName).Password;
            }
            catch
            {
                //Could not be retrieved, it doesn't exist.
                return "";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="credentialName">The name of the credential we are going to store, ex. oAuthToken</param>
        /// <param name="secret">The value of the credential</param>
        public static void SavePassword(string credentialName, string secret)
        {
            var vault = new PasswordVault();
            vault.Add(new PasswordCredential(AppId, credentialName, secret));
        }

        public static void RemoveAllCredentials()
        {
            var vault = new PasswordVault();
            try
            {
                var credentials = vault.FindAllByResource(AppId);
                foreach (var credential in credentials)
                {
                    vault.Remove(credential);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

    }
}
